package com.cloudbroker.bcs.platform.dav.middle.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;

/**
 * <p>
 * Title: HTML相关的正则表达式工具类
 * </p>
 * <p>
 * Description: 包括过滤HTML标记，转换HTML标记，替换特定HTML标记
 * </p>
 * <p>
 * Copyright: Copyright (c) 2006
 * </p>
 * 
 * @author chengRenYin
 * @version 1.0
 * @createtime 2010-1-27
 */

public abstract class HtmlRegexpUtil {
    private final static String regxpForHtml = "<([^>]*)>"; // 过滤所有以<开头以>结尾的标签     
    
    /**
     * 
     * 基本功能：替换标记以正常显示
     * <p>
     * 
     * @param input
     * @return String
     */
    public static String replaceTag(String input) {
        if (!hasSpecialChars(input)) {
            return input;
        }
        StringBuffer filtered = new StringBuffer(input.length());
        char c;
        for (int i = 0; i <= input.length() - 1; i++) {
            c = input.charAt(i);
            switch (c) {
                case '<':
                    filtered.append("&lt;");
                    break;
                case '>':
                    filtered.append("&gt;");
                    break;
                case '"':
                    filtered.append("&quot;");
                    break;
                case '&':
                    filtered.append("&amp;");
                    break;
                default:
                    filtered.append(c);
            }
            
        }
        return (filtered.toString());
    }
    
    /**
     * 
     * 基本功能：判断标记是否存在
     * <p>
     * 
     * @param input
     * @return boolean
     */
    public static boolean hasSpecialChars(String input) {
        boolean flag = false;
        if ((input != null) && (input.length() > 0)) {
            char c;
            for (int i = 0; i <= input.length() - 1; i++) {
                c = input.charAt(i);
                switch (c) {
                    case '>':
                        flag = true;
                        break;
                    case '<':
                        flag = true;
                        break;
                    case '"':
                        flag = true;
                        break;
                    case '&':
                        flag = true;
                        break;
                }
            }
        }
        return flag;
    }
    
    /**
     * 
     * 基本功能：过滤所有以"<"开头以">"结尾的标签
     * <p>
     * 
     * @param str
     * @return String
     */
    public static String filterHtml(String str) {
        Pattern pattern = Pattern.compile(regxpForHtml);
        Matcher matcher = pattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        boolean result1 = matcher.find();
        while (result1) {
            matcher.appendReplacement(sb, "");
            result1 = matcher.find();
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
    
    /**
     * 
     * 基本功能：过滤指定标签
     * <p>
     * 
     * @param str
     * @param tag
     *            指定标签
     * @return String
     */
    public static String fiterHtmlTag(String str, String tag) {
        String regxp = "<" + tag + ">";
        StringBuffer sb = avoidTag(str, regxp);
        regxp = "</" + tag + ">";
        sb = avoidTag(sb.toString(), regxp);
        return sb.toString();
    }

    private static StringBuffer avoidTag(String str, String regxp) {
        Pattern pattern = Pattern.compile(regxp, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
        Matcher matcher = pattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        boolean result1 = matcher.find();
        while (result1) {
            matcher.appendReplacement(sb, "");
            result1 = matcher.find();
        }
        matcher.appendTail(sb);
        return sb;
    }
    
    
    /**
     * 
     * 基本功能：替换指定的标签
     * <p>
     * 
     * @param str
     * @param beforeTag
     *            要替换的标签
     * @param tagAttrib
     *            要替换的标签属性值
     * @return String
     * @如：替换img标签的src属性值为[img]属性值[/img]
     */
    public static String replaceHtmlTag(String str, String beforeTag, String tagAttrib) {
        String regxpForTag = "<\\s*" + beforeTag + "\\s+([^>]*)\\s*>";
        String regxpForTagAttrib = tagAttrib + "=\"([^\"]+)\"";
        Pattern patternForTag = Pattern.compile(regxpForTag);
        Pattern patternForAttrib = Pattern.compile(regxpForTagAttrib);
        Matcher matcherForTag = patternForTag.matcher(str);
        StringBuffer sb = new StringBuffer();
        boolean result = matcherForTag.find();
        while (result) {
            StringBuffer sbreplace = new StringBuffer();
            Matcher matcherForAttrib = patternForAttrib.matcher(matcherForTag.group(1));
            if (matcherForAttrib.find()) {
                matcherForAttrib.appendReplacement(sbreplace, matcherForAttrib.group(1));
            }
            matcherForTag.appendReplacement(sb, sbreplace.toString().trim());
            result = matcherForTag.find();
        }
        matcherForTag.appendTail(sb);
        return sb.toString();
    }  
      
    /**   
     * @param htmlStr  html文本 
     * @param searchAttrib  目标标签中的属性     
     */    
    public static String updateHtmlTag(String htmlStr, String searchAttrib) {     
        String regxpForTag = "<([^>]*)>";//"<\\s*" + searchTag + "\\s+([^>]*)\\s*>";      
        String regxpForTagAttrib = searchAttrib + "\\s*=\\s*[\"|']([^\"|']+)[\"|']";//"=[\"|']([^[\"|']]+)[\"|']";     
        Pattern patternForTag = Pattern.compile(regxpForTag);     
        Pattern patternForAttrib = Pattern.compile(regxpForTagAttrib);     
        Matcher matcherForTag = patternForTag.matcher(htmlStr);     
        StringBuffer sb = new StringBuffer();     
        boolean result = matcherForTag.find();     
        while (result) {     
            StringBuffer sbreplace = new StringBuffer("<");   
            //System.out.println(matcherForTag.group(1));  
            Matcher matcherForAttrib = patternForAttrib.matcher(matcherForTag.group(1));     
              
            if (matcherForAttrib.find()) {
                matcherForAttrib.appendReplacement(sbreplace, "");
            }    
            matcherForAttrib.appendTail(sbreplace);  
            matcherForTag.appendReplacement(sb, sbreplace.toString().trim()+">");  
            result = matcherForTag.find();     
        }     
        matcherForTag.appendTail(sb);     
        return sb.toString();     
    }
    
    /**   
     * @param htmlStr  html文本 
     * @param searchAttrib  目标标签中的属性     
     */    
    public static String updateHtmlTag(String htmlStr, String searchTag, String searchAttrib) {     
        String regxpForTag = "<\\s*" + searchTag + "\\s+([^>]*)\\s*>";      
        String regxpForTagAttrib = searchAttrib + "\\s*=\\s*[\"|']([^\"|']+)[\"|']";//"=[\"|']([^[\"|']]+)[\"|']";     
        Pattern patternForTag = Pattern.compile(regxpForTag);     
        Pattern patternForAttrib = Pattern.compile(regxpForTagAttrib);     
        Matcher matcherForTag = patternForTag.matcher(htmlStr);     
        StringBuffer sb = new StringBuffer();     
        boolean result = matcherForTag.find();     
        while (result) {     
            StringBuffer sbreplace = new StringBuffer("<" + searchTag + " ");
            Matcher matcherForAttrib = patternForAttrib.matcher(matcherForTag.group(1));
            boolean flag = false;
            if (matcherForAttrib.find()) {
                String value = matcherForAttrib.group(1);
                if(regxpForTagAttrib.contains("src")){
                    if(!value.startsWith("http://")){
                        matcherForTag.appendReplacement(sb, "");
                        flag = true;
                    }else{
                        String src = ConfigValues.getInterfaceOssAddr();//"http://127.0.0.1:21700/func_file_download";
                        String s = getUrl(src);
                        String s1 = getUrl(value);
                        if(!s.equals(s1)){
                            matcherForTag.appendReplacement(sb, "");
                            flag = true;
                        }
                    }                   
                }else if(regxpForTagAttrib.contains("AllowScriptAccess")){
                    matcherForAttrib.appendReplacement(sbreplace, "AllowScriptAccess=\"samedomain\"");
                }
            }    
            matcherForAttrib.appendTail(sbreplace);
            if(!flag){
                matcherForTag.appendReplacement(sb, sbreplace.toString().trim()+">");
            }              
            result = matcherForTag.find();     
        }     
        matcherForTag.appendTail(sb);     
        return sb.toString();     
    }

    private static String getUrl(String value) {
        int a = value.indexOf("/",value.indexOf("/")+1);
        int b = value.indexOf("/",a+1);
        String s = value.substring(a+1,b);
        return s;
    }
    
}
